package com.binc.testspring.study.nio.groupchat;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * FileName: GroupChatClient 客户端
 * Autho: binC
 * Date:  2022/4/15 15:38
 */
@Slf4j
public class GroupChatClient {

    private final static String HOST = "127.0.0.1";
    private final static int PORT = 19999;
    private Selector selector;
    private SocketChannel socketChannel;
    private String name;

    public static void main(String[] args) throws IOException {
        GroupChatClient groupChatClient = new GroupChatClient();
        new Thread(()->{
            while (true){
                try {
                    groupChatClient.readInfo();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        } ).start();

        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()){
            String info = sc.nextLine();
            groupChatClient.sendInfo(info);
        }
    }

    public GroupChatClient() {

        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open(new java.net.InetSocketAddress(HOST, PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            name = socketChannel.getLocalAddress().toString().substring(1); // 这个东西不是很重要,我们就是用它来表示客户端的名字   如:
            log.info("客户端名字: {}", name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void sendInfo(String info) throws IOException {
        info = name+ "说: "+info;
        socketChannel.write(ByteBuffer.wrap(info.getBytes()));

    }

    public void readInfo(){
        try {
            int ready = selector.select();
            if (ready > 0) {
                // 读取服务器发送的消息
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                if (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        String msg = "";
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        while (channel.read(buffer) > 0) {
                            // buffer.flip();
                            msg += new String(buffer.array(), 0, buffer.limit());
                            // buffer.clear();
                        }
                            log.info("----------------收到消息: {}---------------", msg);
                    }
                    iterator.remove();
                }
            }


        }catch (Exception e){
            e.printStackTrace();
        }

    }


}
